<template>
  <div class="like-container">
    <h2 class="section-title animate__animated animate__fadeIn">
      <t-icon name="heart" class="title-icon" />
      最近点赞
    </h2>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>
    
    <div v-else-if="likedContents.length === 0" class="empty-state animate__animated animate__fadeIn">
      <t-icon name="info-circle" class="empty-icon" />
      <p>暂无点赞内容</p>
    </div>
    
    <div v-else class="liked-content-list">
      <div 
        v-for="item in likedContents" 
        :key="item.contentType + item.content.id" 
        class="liked-item animate__animated animate__fadeIn"
        :class="{'article': item.contentType === 'article', 'question': item.contentType === 'question', 'answer': item.contentType === 'answer'}"
      >
        <div class="content-type-badge">
          <t-icon :name="getContentTypeIcon(item.contentType)" />
          <span>{{ getContentTypeLabel(item.contentType) }}</span>
        </div>
        
        <div class="content-header" @click="navigateToContent(item)">
          <h3 class="content-title">{{ item.content?.title || '内容已删除' }}</h3>
          <span class="liked-time">{{ formatTime(item.likedAt) }}</span>
        </div>
        
        <div class="content-preview" @click="navigateToContent(item)">
          <p v-if="item.contentType === 'article' && item.content?.description">{{ truncateText(item.content.description, 150) }}</p>
          <p v-else-if="item.content?.content">{{ truncateText(stripHtml(item.content.content), 150) }}</p>
          <p v-else class="no-content">内容不可用</p>
        </div>
        
        <div class="content-stats">
          <div class="stat-item">
            <t-icon name="heart-filled" class="stat-icon like-icon" />
            <span>{{ item.content?.likeCount || 0 }}</span>
          </div>
          <div class="stat-item">
            <t-icon name="star" class="stat-icon" />
            <span>{{ item.content?.favoriteCount || 0 }}</span>
          </div>
          <div class="stat-item">
            <t-icon name="chat" class="stat-icon" />
            <span>{{ item.content?.commentCount || 0 }}</span>
          </div>
          <div v-if="item.contentType === 'question'" class="stat-item">
            <t-icon name="help-circle" class="stat-icon" />
            <span>{{ item.content?.answerCount || 0 }}</span>
          </div>
        </div>
      </div>
      
      <el-pagination
        v-if="likedContents.length > pageSize"
        background
        layout="prev, pager, next"
        :total="likedContents.length"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
        class="pagination"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getLikedContent } from '@/api/userApi';
import { useUserStore } from '@/stores/userStore';
import { storeToRefs } from 'pinia';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const { profile } = storeToRefs(userStore);

const likedContents = ref([]);
const loading = ref(true);
const currentPage = ref(1);
const pageSize = ref(10);

onMounted(() => {
  fetchLikedContents();
});

// 添加 watch 来监听路由参数变化
watch(
  () => route.params.id,
  (newId, oldId) => {
    if (newId && newId !== oldId) {
      currentPage.value = 1; // 重置页码
      fetchLikedContents();
    }
  }
);

const fetchLikedContents = async () => {
  loading.value = true;
  try {
    const userId = route.params.id;
    if (!userId) {
      ElMessage.warning('用户ID不存在');
      return;
    }
    
    const response = await getLikedContent(userId, currentPage.value, pageSize.value);
    
    // 直接使用返回的数据，不需要二次查询
    likedContents.value = response.data || [];
  } catch (error) {
    console.error('获取点赞内容出错:', error);
    ElMessage.error('获取点赞内容失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchLikedContents();
};

const getContentTypeIcon = (type) => {
  switch (type) {
    case 'article': return 'book';
    case 'question': return 'help-circle';
    case 'answer': return 'chat';
    default: return 'file';
  }
};

const getContentTypeLabel = (type) => {
  switch (type) {
    case 'article': return '文章';
    case 'question': return '问题';
    case 'answer': return '回答';
    default: return '内容';
  }
};

const navigateToContent = (item) => {
  if (!item.content) {
    ElMessage.warning('该内容不可用或已被删除');
    return;
  }
  
  switch (item.contentType) {
    case 'article':
      router.push(`/home/article/${item.content.id}`);
      break;
    case 'question':
      router.push(`/home/question/${item.content.id}`);
      break;
    case 'answer':
      // 使用问题ID和回答ID导航
      router.push(`/home/question/${item.question.id}?answerId=${item.content.id}`);
      break;
    default:
      ElMessage.warning('无法导航到此类型的内容');
  }
};

const formatTime = (timeString) => {
  if (!timeString) return '';
  
  const date = new Date(timeString);
  const now = new Date();
  const diffMs = now - date;
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHour = Math.floor(diffMin / 60);
  const diffDay = Math.floor(diffHour / 24);
  
  if (diffDay > 30) {
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
  } else if (diffDay > 0) {
    return `${diffDay}天前`;
  } else if (diffHour > 0) {
    return `${diffHour}小时前`;
  } else if (diffMin > 0) {
    return `${diffMin}分钟前`;
  } else {
    return '刚刚';
  }
};

const truncateText = (text, maxLength) => {
  if (!text) return '';
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
};

const stripHtml = (html) => {
  if (!html) return '';
  return html.replace(/<[^>]*>/g, '');
};
</script>

<style scoped>
.like-container {
  padding: 20px;
  max-width: 900px;
  margin: 0 auto;
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  color: #333;
  font-size: 1.5rem;
}

.title-icon {
  margin-right: 10px;
  color: #ff6b6b;
}

.loading-container {
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  background: #f9f9f9;
  border-radius: 8px;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.liked-content-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.liked-item {
  position: relative;
  padding: 16px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
  overflow: hidden;
  border-left: 4px solid #ddd;
}

.liked-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.liked-item.article {
  border-left-color: #4caf50;
}

.liked-item.question {
  border-left-color: #2196f3;
}

.liked-item.answer {
  border-left-color: #ff9800;
}

.content-type-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  display: flex;
  align-items: center;
  padding: 4px 8px;
  background: #f5f5f5;
  border-radius: 16px;
  font-size: 0.75rem;
  color: #666;
}

.content-type-badge .t-icon {
  margin-right: 4px;
}

.content-header {
  margin-bottom: 12px;
  cursor: pointer;
}

.content-title {
  margin: 0 0 8px 0;
  font-size: 1.2rem;
  color: #333;
}

.liked-time {
  font-size: 0.8rem;
  color: #999;
}

.content-preview {
  margin-bottom: 16px;
  color: #666;
  font-size: 0.9rem;
  line-height: 1.5;
  cursor: pointer;
}

.no-content {
  font-style: italic;
  color: #999;
}

.content-stats {
  display: flex;
  gap: 16px;
  padding-top: 12px;
  border-top: 1px solid #eee;
}

.stat-item {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 0.9rem;
}

.stat-icon {
  margin-right: 4px;
}

.like-icon {
  color: #ff6b6b;
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .like-container {
    padding: 12px;
  }
  
  .liked-item {
    padding: 12px;
  }
  
  .content-title {
    font-size: 1rem;
  }
}
</style>    